package com.juyu.miliao.api.service;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations.TypedTuple;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;

/**
 * 排行榜redis
 */
@Service
public class RedisTemplateService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    public void setMUserSort(long userId, double value) {
        //m:day:xxxx-xx-xx
        stringRedisTemplate.opsForZSet().incrementScore("m:day:"+LocalDate.now().toString(),userId+"",value);
        stringRedisTemplate.opsForZSet().incrementScore("m:week",userId+"",value);
        stringRedisTemplate.opsForZSet().incrementScore("m:sum",userId+"",value);
    }

    public void setVUserSort(long userId, double value) {
        stringRedisTemplate.opsForZSet().incrementScore("v:day",userId+"",value);
        stringRedisTemplate.opsForZSet().incrementScore("v:week",userId+"",value);
        stringRedisTemplate.opsForZSet().incrementScore("v:sum",userId+"",value);
    }

    public void setTUserSort(long userId,long time){
        stringRedisTemplate.opsForZSet().incrementScore("t:day",userId+"",time);
        stringRedisTemplate.opsForZSet().incrementScore("t:week",userId+"",time);
        stringRedisTemplate.opsForZSet().incrementScore("t:sum",userId+"",time);
    }

    public Map<String, String> getMUserSort(String key, int startNum, Integer pageCount) {
        Map<String, String> maps = new LinkedHashMap<String, String>();
        Set<TypedTuple<String>> tuples = stringRedisTemplate.opsForZSet().reverseRangeWithScores(key,startNum,pageCount);
        Iterator<TypedTuple<String>> iterator = tuples.iterator();
        while (iterator.hasNext()) {
            TypedTuple<String> typedTuple = iterator.next();
            String score = typedTuple.getScore().toString();
            maps.put(typedTuple.getValue().toString(), score.substring(0, score.indexOf(".")));
        }
        return maps;
    }

    public Long removeUserSortDay(String key){
        return stringRedisTemplate.opsForZSet().removeRange(key, 0, -1);
    }

    public Long getUserSortReverseRank(long tokenUserId, String rediskey) {
        return stringRedisTemplate.opsForZSet().reverseRank(rediskey,tokenUserId+"");
    }
}
